package com.atguigu.lease.web.app.service.impl;


import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.ThreadLocalLoginUserContext;
import com.atguigu.lease.common.result.CodeResult;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.HttpUtils;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.common.utils.VerifyCodeUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.web.app.controller.utils.CodeUtils;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.jsonwebtoken.lang.Assert;
import org.apache.http.HttpResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    UserInfoMapper userInfoMapper;

    @Override
    public void getCodeFromAl(String phone) {
        try {
            //获取验证码
            CodeResult codeNumber = CodeUtils.getCodeNumber(phone);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public String checkCodeToLogin(LoginVo loginVo) {
        //验证验证码是否有效
        String token = null;
        try {
            String result = CodeUtils.CheckCode(loginVo.getCode(), loginVo.getPhone());
            Assert.isTrue(result.equals("PASS"), "验证码错误");
            //验证码正确
            //判断用户是否为新人
            UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<>(UserInfo.class).eq(UserInfo::getPhone, loginVo.getPhone()));
            Long id = userInfo.getId();
            if (userInfo == null) {
                //保存到数据库
                userInfo = new UserInfo();
                userInfo.setPhone(loginVo.getPhone());
                userInfoMapper.insert(userInfo);
                id = userInfo.getId();
            }
            //令牌
            String nickname = userInfo.getNickname();
            token = JwtUtil.createToken(id, nickname);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }
}
